#!/bin/sh

CHECK=true
LINK=false
CLONE=false

. "$TEST_SHELL_PATH/dbops-major-version-upgrade/abstract-major-version-upgrade"

shell_unit_test() {
  shell_unit_test_dbops_major_version_upgrade
  check_dbops_result
}

mock kubectl kubectl_mock_overwrite

kubectl_mock_overwrite() {
  mokked
  case "$*" in
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ if .status.dbOps }}{{ if .status.dbOps.$OP_NAME }}true{{ end }}{{ end }}")
    printf true
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ .status.dbOps.$OP_NAME.targetPostgresVersion }}")
    printf %s "$TARGET_VERSION"
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ .status.dbOps.$OP_NAME.sourcePostgresVersion }}")
    printf %s "$SOURCE_VERSION"
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ .status.dbOps.$OP_NAME.sourceSgPostgresConfig }}")
    printf %s "postgresconf"
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ if .status.dbOps.majorVersionUpgrade.sourceBackupPath }}{{ .status.dbOps.majorVersionUpgrade.sourceBackupPath }}{{ end }}")
    printf %s "sgbackup.stackgres.io/$CLUSTER_NAMESPACE/$CLUSTER_NAME/${SOURCE_VERSION%.*}"
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ .status.dbOps.$OP_NAME.sourceReplicationMode }}")
    printf %s async
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ with .status.dbOps.$OP_NAME.initialInstances }}{{ . }}{{ end }}")
    printf '[test-0 test-1]'
    ;;
    ("get $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --template={{ with .status.dbOps.$OP_NAME.primaryInstance }}{{ . }}{{ end }}")
    printf 'test-0'
    ;;
    ("patch $CLUSTER_CRD_NAME.$CRD_GROUP -n $CLUSTER_NAMESPACE $CLUSTER_NAME --type=json -p "*"{\"op\":\"replace\",\"path\":\"/status/dbOps/majorVersionUpgrade"*)
    ;;
    ("logs -n $CLUSTER_NAMESPACE $CLUSTER_NAME-"*" -c $MAJOR_VERSION_UPGRADE_CONTAINER_NAME")
    echo "Major version upgrade check performed"
    ;;
    ("get pod -n $CLUSTER_NAMESPACE $CLUSTER_NAME-"*" -o json")
    echo '{
      "status": {
        "initContainerStatuses": [{
          "name": "major-version-upgrade"
        }]
      }
    }'
    ;;
    ("get sts -n $CLUSTER_NAMESPACE $CLUSTER_NAME -o json")
    echo '{
      "spec": {
        "template": {
          "metadata": {
            "annotations": {
              "stackgres.io/postgresql-version": "12.6"
            }
          },
          "spec": {
            "initContainers": [{
              "name": "major-version-upgrade",
              "env": [{
                "name": "ROLLBACK",
                "value": "true"
              }]
            }]
          }
        }
      }
    }'
    ;;
    *)
    not_mokked
    ;;
  esac
}
